package com.hsgc.advice;

import cn.hutool.json.JSONUtil;
import com.hsgc.dto.ResponseDTO;
import com.hsgc.exception.BizException;
import com.hsgc.info.PageInfo;
import com.hsgc.threadlocal.LocalPageInfoUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

//对controller的一个增强 ResponseBodyAdvice响应的结果增强
@RestControllerAdvice
public class MyResponseAdvice implements ResponseBodyAdvice<Object> {
    //支持的方法 默认所有的方法都不支持增强 改成true
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        //代表增强接口的开关
        return true;
    }
    //如果有错误信息
    @ExceptionHandler
    public Object processException(Exception ex){
        if(ex instanceof BizException){
            BizException bizException= (BizException) ex;
            return ResponseDTO.error(bizException.getCode(), ex.getMessage());
        }
        ResponseDTO dto=ResponseDTO.error(99,ex.getMessage());
        return dto;
    }



    @Override
    public Object beforeBodyWrite(Object bady,
                                  MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        //解决双层嵌套问题
        if(bady instanceof ResponseDTO){
            return bady;
        }

        ResponseDTO dto=ResponseDTO.success(bady);
        PageInfo pageInfo= LocalPageInfoUtil.get();
        if(pageInfo !=null){
            HashMap<Object,Object> map=new HashMap<>();
            map.put("total",pageInfo.getTotal());
            map.put("items",bady);
            dto=ResponseDTO.success(map);
            LocalPageInfoUtil.remove();
        }
        //证明我们的接口返回的是String
        if(aClass == StringHttpMessageConverter.class){
            //统一修改为json串格式
            return JSONUtil.toJsonStr(dto);
        }

        return dto;
    }
}
